package penguin

import (
	jsoniter "github.com/json-iterator/go"
	"github.com/kataras/iris/v12"
	"os"
	"strconv"
	"time"
)

var TokenDuration time.Duration

func Config(app *iris.Application) iris.Runner {
	//configOrm()
	//configRedis()
	//configMsm()
	//configOss()
	configWechat()
	//standardInit()
	configLog(app)
	return configurator(app)
}

func configurator(app *iris.Application) iris.Runner {
	var data = struct {
		Port          int64  `json:"port"`
		Tls           bool   `json:"tls"`
		CertFile      string `json:"certFile"`
		KeyFile       string `json:"keyFile"`
		TokenDuration int64  `json:"tokenDuration"`
	}{}
	loadConfigJson("config/app.json", &data)
	TokenDuration = time.Duration(data.TokenDuration) * time.Second
	var runner iris.Runner
	if data.Tls {
		runner = iris.TLS(":"+strconv.FormatInt(data.Port, 10), data.CertFile, data.KeyFile)
	} else {
		runner = iris.Addr(":" + strconv.FormatInt(data.Port, 10))
	}
	return runner
}

func loadConfigJson(path string, data interface{}) {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		panic(err)
	}
	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	fileConfig, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	decoder := json.NewDecoder(fileConfig)
	err = decoder.Decode(&data)
	if err != nil {
		panic(err)
	}
	_ = fileConfig.Close()
	return
}
